import { _decorator, Component, instantiate, Label, Node, Prefab } from 'cc';
import { PlayerController } from './PlayerController';
const { ccclass, property } = _decorator;

enum BLOCK_TYPE{
    BLOCK_NONE,
    BLOCK_WHITE
}

enum GAME_STATE{
    GA_MENU,
    GA_PALYING
}

@ccclass('GameManager')
export class GameManager extends Component {
	@property(Prefab)
	public boxPrefab: Prefab = null

	private _roadLength: number = 50
	private _road: BLOCK_TYPE[] = []

	@property(PlayerController)
	public playerController: PlayerController = null

	@property(Node)
	public startMenuLabel: Node = null

	@property(Label)
	public stepScoreLabel: Label = null

	start() {
		this.setGameStats(GAME_STATE.GA_MENU)
		this.playerController.node.on('jumpEnd', this.onUpdateStepScore, this)
	}

	setGameStats(value: GAME_STATE) {
        if (value === GAME_STATE.GA_MENU) {
            this.startMenuLabel.active = true;
            this.stepScoreLabel.string = "0";
            this.playerController.playerReset();
			this.playerController.checkIsCanController(false)
        } else if (value === GAME_STATE.GA_PALYING) {
            this.startMenuLabel.active = false
			this.playerController.checkIsCanController(true)
			this.generateBoxes()
		}
	}

	setPlaying() {
		this.setGameStats(GAME_STATE.GA_PALYING)
		
	}

    onUpdateStepScore(score: number) {
         this.stepScoreLabel.string = score.toString()
        this.checkGameOver(score);
		
    }
    
    checkGameOver(totalScore: number) {
        console.log("checkGameOver", totalScore,this._road[totalScore])
        if (totalScore >= this._roadLength) {
			this.setGameStats(GAME_STATE.GA_MENU)
        } else {
            if (this._road[totalScore] === BLOCK_TYPE.BLOCK_NONE) {
                this.setGameStats(GAME_STATE.GA_MENU)
            }
        }
    }

	generateBoxes() {
		this.node.removeAllChildren()
		this._road = []
		this._road.push(BLOCK_TYPE.BLOCK_WHITE)

		for (let i = 1; i < this._roadLength; i++) {
			if (this._road[i - 1] == BLOCK_TYPE.BLOCK_NONE) {
				this._road.push(BLOCK_TYPE.BLOCK_WHITE)
			} else {
				const randomValue = Math.round(Math.random())
				this._road.push(
					randomValue === 0 ? BLOCK_TYPE.BLOCK_NONE : BLOCK_TYPE.BLOCK_WHITE
				)
			}
		}

		for (let i = 1; i < this._roadLength; i++) {
			if (this._road[i] == BLOCK_TYPE.BLOCK_WHITE) {
				const box = instantiate(this.boxPrefab)
				this.node.addChild(box)
				box.setPosition(i * 40, 0, 0)
			}
		}
	}

    update(deltaTime: number) { }
    onDestroy() {
        this.playerController.node.off('jumpEnd', this.onUpdateStepScore, this)
    }

}


